package sch.frog.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import java.util.UUID;

/**
 * base64 编码解码
 * @author frogif
 * since: java 1.8
 */
public class Base64ImageUtil {
	
	/**
	 * 根据base64获取mime
	 * @param base64
	 * @return
	 */
	public static String getMIMEType(String base64) {
		String[] baseStrs = base64.split(",");
		return baseStrs[0].split(";")[0];
	}
	
	/**
	 * 根据base64获取文件后缀
	 * @param base64
	 * @return
	 */
	public static String getFileSuffix(String base64) {
		String mime = getMIMEType(base64);
		return mime.split("/")[1];
	}
	
	/**
	 *	Base64 转 文件
	 * 	保存至user.dir路径下
	 * @param base64
	 * @return
	 * @throws IOException 
	 */
	public static File convertToFile(String base64) throws IOException {
		return convertToFile(base64, null);
	}
	
	/**
	 * Base64 转 文件
	 * @param base64
	 * @param path	保存路径, 如果为空, 则保存至user.dir下
	 * @return
	 * @throws IOException
	 */
	public static File convertToFile(String base64, String path) throws IOException {
		String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + getFileSuffix(base64);	// 生成文件名
		
		File file = null;
		if(path != null) {
			file = new File(path, fileName);
		}else {
			file = new File(fileName);
		}
		
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		convertToOutputStream(base64, fileOutputStream);
		fileOutputStream.close();
		
		return file;
	}
	
	/**
	 * Base64 转 字节流
	 * @param base64
	 * @param outputStream	输出流容器
	 */
	public static void convertToOutputStream(String base64, OutputStream outputStream) {
		String[] baseStrs = base64.split(",");
		
		Decoder decoder = Base64.getDecoder();
		byte[] b = new byte[0];
		b = decoder.decode(baseStrs[1].trim());	// base64正文
		
		for(int i = 0; i < b.length; ++i) {
			if (b[i] < 0) {
				b[i] += 256;
			}
		}
		
		try{
			outputStream.write(b);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 *	文件流 转 Base64
	 * @param input
	 * @param mime	MIME类型
	 * @return
	 * @throws IOException
	 */
	public static String convertToBase64(InputStream input, String mime) throws IOException {
		byte[] buffer = new byte[100];
		int len = 0;
		
		Encoder encoder = Base64.getEncoder();
		
		ByteArrayOutputStream output = new ByteArrayOutputStream();	//ByteArrayOutputStream无需关闭, 或者说关闭不会起作用, 由jvm自动回收
		
		while((len = input.read(buffer)) != -1) {
			output.write(buffer, 0, len);
		}
		
		String base64 = "data:" + mime + ";base64," + encoder.encodeToString(output.toByteArray());

		return base64;
	}

}
